/*
** b_echo.c for 42SH in /home/fillin_j//42SH
** 
** Made by jennifer fillinger
** Login   <fillin_j@epitech.net>
** 
** Started on  Tue Apr  3 22:49:42 2012 jennifer fillinger
** Last update Thu Apr 12 17:13:49 2012 julien linglain
*/

#include <stdlib.h>
#include "mysh.h"

int		my_print_value(char *key, t_list *env)
{
  char		*value;

  value = getvalue(env, key);
  if (value != NULL)
    my_putstr(value);
  if (value == NULL)
    {
      my_puterror(key);
      my_puterror(": Undefined variable.");
      return (EXIT_FAILURE);
    }
  return (EXIT_SUCCESS);
}

int		my_echokey(char *s, t_list *env, int i)
{
  char		*key;
  int		j;
  int		k;

  k = 0;
  j = i;
  while (s[i] != '\0' && s[i] != ' ' && s[i] != '\t')
    i++;
  if (i == j + 1)
    {
      my_putchar('$');
      return (EXIT_FAILURE);
    }
  key = xmalloc(sizeof(char) * (i - j + 1));
  j++;
  while (s[j] != '\0' && s[j] != ' ' && s[j] != '\t')
    {
      key[k] = s[j];
      j++;
      k++;
    }
  key[k] = '\0';
  my_print_value(key, env);
  return (i);
}

int		my_echo(char *s, t_list *env)
{
  int		i;

  i = 0;
  while (s[i] != '\0')
    {
      if (s[i] == '$')
	{
	  i = my_echokey(s, env, i);
	}
      if (i < my_strlen(s))
	my_putchar(s[i]);
      i++;
    }
  return (EXIT_SUCCESS);
}

int		b_echo(int ac, char *s, char **av, t_list *env)
{
  int		i;
  int		n;

  i = 1;
  n = 0;
  while (i != ac)
    {
      if (my_strcmp(av[i], "-n") == 0 && n != 1)
	{
	  i++;
	  n++;
	}
      my_echo(av[i], env);
      if (i < ac - 1)
	my_putchar(' ');
      i++;
    }
  if (n == 0)
    my_putchar('\n');
  return (EXIT_SUCCESS);
}
